<template>
  <div class="dataReport">
    <div class="categoryBox">
      <div class="categoryHeaderBox flex">
        <span style="font-weight: 600">参数分类</span>
        <el-tooltip class="iconTip" effect="dark" content="新增分类" placement="right">
          <i class="el-icon-plus" @click="addCategory()"></i>
        </el-tooltip>
      </div>

      <!--   左侧树 -->
      <el-tree
        v-loading="loading"
        :data="categoryList"
        :props="defaultProps"
        node-key="key"
        @node-click="handleNodeClick"
        :filter-node-method="filterNode"
        :highlight-current="true"
        ref="reportTree"
        default-expand-all
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span style="width: 80%" class="more" :class="{'color-blue': !node.parent.parent}">
            <span
              class="jstarfont"
              :class="{'jstar-wenjianjia': !node.parent.parent}"
              :style="{marginRight: !node.parent.parent? '5px' : '5px'}"
            ></span>
            <el-tooltip :content="node.label" placement="top" effect="dark">
              <span>{{ node.label }}</span>
            </el-tooltip>
          </span>
          <span class="reportIconBox">
            <el-popover
              :popper-class="'reportPopover'"
              placement="bottom"
              width="30"
              trigger="hover"
            >
              <div class="popBox">
                <el-tooltip
                  v-if="data.isLeaf === 0"
                  class="item"
                  effect="dark"
                  content="新增子目录"
                  placement="right"
                >
                  <i class="el-icon-plus" @click.stop.prevent="addCategory(data)"></i>
                </el-tooltip>
                <i class="el-icon-delete" @click.stop.prevent="deleteCategory(data)"></i>
                <i class="el-icon-edit-outline" @click.stop.prevent="editCategory(data)"></i>

                <!-- <el-tooltip class="item" effect="dark" content="添加参数" placement="right">
                  <i class="el-icon-folder-add" @click.prevent="dialogVisible = true; currentCategoryId = data.key"></i>
                </el-tooltip>-->
              </div>
              <span slot="reference" class="jstarfont jstar-gengduo finger"></span>
            </el-popover>
          </span>
        </span>
      </el-tree>
    </div>

    <div class="reportBox">
      <div class="contentBox">
        <el-form :model="searvhValue" ref="queryForm" :inline="true" label-width="80px" size="mini">
          <el-form-item label="参数名称">
            <el-input
              placeholder="请输入参数名称"
              clearable
              style="width: 200px"
              v-model="searvhValue.parameterName"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="参数编码">
            <el-input
              placeholder="请输入参数编码"
              clearable
              style="width: 200px"
              v-model="searvhValue.parameterCode"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <!-- <el-form-item label="参数来源">
            <el-select v-model="searvhValue.parameterType" placeholder="请选择参数来源">
              <el-option
                v-for="item in parameterTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-input
              placeholder="请输入参数名称"
              clearable
              style="width: 200px"
              v-model="searvhValue.parameterType"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>-->

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>

          <!-- <el-form-item class="absolute" style="right: 8px">
            <el-button v-if="currentCategoryId" type="primary" icon="el-icon-plus" size="mini" @click="dialogVisible = true">新增参数</el-button>
          </el-form-item>-->
        </el-form>

        <el-tabs style="width: 100%" v-model="activeName" @tab-click="handleTabsClick" type="card">
          <el-tab-pane
            v-for="item in parameterTypeList"
            :key="item.value"
            :label="item.name"
            :name="item.value"
          >
            <div style="width: 100%" v-loading="loading2">
              <el-button
                v-if="activeName != 'BOT'"
                type="primary"
                style="margin-bottom: 10px"
                icon="el-icon-plus"
                size="mini"
                @click="dialogVisible = true"
              >新增参数</el-button>
              <tableModule
                :key="new Date().getTime()"
                :dataList="dataList"
                :type="activeName"
                @deleteItem="deleteItem"
                @editItem="editItem"
                @setItem="setItem"
              ></tableModule>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-pagination
        style="float: right;margin-top: 20px"
        :current-page.sync="pageNum"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalSize"
      ></el-pagination>
    </div>

    <!--分类弹窗 -->
    <el-dialog :title="isEdit ? '修改分类' : '新增分类'" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="addInfo" :rules="addInfoRules" ref="addInfo">
        <el-form-item label="名称" :label-width="'80px'" prop="name">
          <el-input v-model="addInfo.name" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="上级" :label-width="'80px'" prop="parentId">
          <el-input v-model="addInfo.parentId" disabled placeholder="一级菜单非必填项" autocomplete="off"></el-input>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addInfo')">确 定</el-button>
      </div>
    </el-dialog>

    <!--参数弹窗 -->
    <el-dialog title :visible.sync="dialogVisible" width="60%">
      <div style="height: 600px">
        <paramsDefinition
          v-if="dialogVisible"
          ref="paramsDefinition"
          :editData="editData"
          @queryNewList="queryNewList"
          :dialog.sync="dialogVisible"
          :id="currentCategoryId"
          :type="activeName"
        ></paramsDefinition>
      </div>
      <span slot="footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
        <el-button type="primary" @click="submitDefinition">确定提交</el-button>
      </span>
    </el-dialog>

    <!-- 参数值设置 -->
    <el-dialog
      v-if="settingData"
      :title="settingData.parameterName + '值设置'"
      :visible.sync="settingVisible"
      width="40%"
    >
      <div style="width: 100%">
        <div style="margin-bottom: 10px">当前使用值</div>
        <el-table border :data="currentUsingData" style="width: 100%">
          <el-table-column prop="parameterValue" label="变量值"></el-table-column>
          <el-table-column prop="effectiveStart" label="生效时间"></el-table-column>
          <el-table-column prop="effectiveEnd" label="失效时间"></el-table-column>
        </el-table>
        <div style="margin: 20px 0 5px 0; height: 30px; line-height: 30px">
          <span>维护记录</span>
          <el-button
            style="float: right"
            type="primary"
            size="mini"
            @click="addValueVisible = true"
          >新 增</el-button>
        </div>
        <el-table border :data="recordValueData" style="width: 100%">
          <el-table-column prop="parameterValue" label="变量值"></el-table-column>
          <el-table-column prop="effectiveStart" label="生效时间"></el-table-column>
          <el-table-column prop="effectiveEnd" label="失效时间"></el-table-column>
          <!-- <el-table-column label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="judgeRecordStatus(scope.row)[0]">{{ judgeRecordStatus(scope.row)[1] }}</el-tag>
            </template>
          </el-table-column>-->
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-popconfirm title="确定删除这条记录吗？" @confirm="deleteRecord(scope.row.id)">
                <span slot="reference" class="jstarfont jstar-shanchutianchong finger"></span>
              </el-popconfirm>
              <span
                style="margin-left: 10px"
                class="jstarfont jstar-bianji1 finger"
                @click="editRecord(scope.row)"
              ></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 新增记录 -->
    <el-dialog title="新增值" :visible.sync="addValueVisible" width="30%">
      <div>
        <el-form
          :model="addValueData"
          label-width="100px"
          :rules="addValueDataRules"
          ref="addValueData"
        >
          <el-form-item label="参数值" prop="parameterValue">
            <el-input style="width: 200px" v-model="addValueData.parameterValue"></el-input>
          </el-form-item>

          <el-form-item label="生效时间" prop="effectiveStart">
            <el-date-picker
              v-model="addValueData.effectiveStart"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="失效时间" prop="effectiveEnd">
            <el-date-picker
              v-model="addValueData.effectiveEnd"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="submitAddValue('addValueData')">确定提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import selectMemberTree from '@/components/selectMemberTree/selectMemberTree'
import contentNavModule from '@/components/contentNavModule/contentNavModule.vue'
import paramsDefinition from './params/index.vue'
import tableModule from './params/tableTemplate.vue'
export default {
  components: {
    contentNavModule,
    selectMemberTree,
    paramsDefinition,
    tableModule,
  },
  name: 'dataReport',
  data() {
    return {
      categoryList: null,
      currentCategoryId: null,
      defaultProps: {
        children: 'children',
        label: 'title',
      },
      filterText: '',
      dialogFormVisible: false,
      addInfo: {
        //分类
        name: '',
        parentId: '',
        id: '',
      },

      addInfoRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'change' }],
      },
      /* 报表模块 */
      modeType: 1,
      dataList: [],
      /* 新建报表 */
      menuitem: 'datainfo',
      addUrl: '/jmreport/index/',
      /* 编辑报表 */
      isEdit: false,
      /* 报表授权 */
      openAuthorize: false,
      currentReportId: '',
      currentReportUser: [],
      loading: false,
      loading2: false,
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      /* 搜索信息 */
      searvhValue: {
        parameterName: '',
        parameterCode: '',
      },
      /* 参数来源 */
      // parameterTypeList: [
      //   {value: "BILL", label: "单据参数"},
      //   {value: "BASE", label: "基础参数"},
      //   {value: "BOT", label: "系统参数"},
      //   {value: "ASSEMBLE", label: "组合参数"}
      // ],
      /* 当前用户id */
      userId: 1,
      /* 报表修改目录 */
      openChangeCategory: false,
      currentChangeCategoryId: null,
      checkedId: null,

      /* **************************** */
      dialogVisible: false,
      editData: null,
      parameterTypeList: [
        { name: '基础参数', value: 'BASE' },
        { name: '组合参数', value: 'ASSEMBLE' },
        { name: '系统参数', value: 'BOT' },
      ],
      activeName: 'BASE',
      /* 设置参数值 */
      settingVisible: false,
      settingData: null,
      currentUsingData: [],
      recordValueData: [],
      addValueVisible: false,
      addValueData: {
        parameterValue: '',
        effectiveStart: '',
        effectiveEnd: '',
      },
      addValueDataRules: {
        parameterValue: [
          { required: true, message: '请输入值', trigger: 'blur' },
        ],
        effectiveStart: [
          { required: true, message: '请选择生效时间', trigger: 'change' },
        ],
        effectiveEnd: [
          { required: true, message: '请选择失效时间', trigger: 'change' },
        ],
      },
    }
  },
  watch: {
    filterText(val) {
      this.$refs.reportTree.filter(val)
    },
    dialogFormVisible(val) {
      if (!val) {
        this.resetForm('addInfo')
      }
    },
    // settingVisible (value) {
    //   if (!value) {
    //     this.currentUsingData = []
    //   }
    // },
    pageNum: {
      deep: true,
      handler: function () {
        this.queryAllReportByType()
      },
    },
    dialogVisible: {
      deep: true,
      handler: function (value) {
        if (!value) {
          this.editData = null
        }
      },
    },
    addValueVisible: {
      deep: true,
      handler: function (value) {
        if (!value) {
          this.addValueData = {
            parameterValue: '',
            effectiveStart: '',
            effectiveEnd: '',
          }
        }
      },
    },
    settingVisible: {
      deep: true,
      handler: function (value) {
        if (!value) {
          this.currentUsingData = []
          // this.$forceUpdate()
        }
      },
    },
  },
  computed: {},
  created() {
    this.getCatalogue()
    // this.queryAllReportByType()
  },
  methods: {
    /* 修改 */
    editRecord(data) {
      this.addValueVisible = true
      this.addValueData = data
    },
    /* tabs切换 */
    handleTabsClick(tab) {
      this.activeName = tab.name
      this.$nextTick(() => {
        this.queryAllReportByType()
      })
    },
    /* 提交参数录入 */
    submitDefinition() {
      this.$refs.paramsDefinition.submintForm()
    },
    /* 子组件调用请求方法 */
    queryNewList() {
      this.queryAllReportByType()
    },
    /* 编辑参数 */
    editItem(data) {
      let newData = JSON.parse(JSON.stringify(data))
      // newData.calculatorText = ''
      // newData.calculator = ''
      newData.arguments = []
      this.editData = newData
      this.dialogVisible = true
    },
    /* 设置参数 */
    async setItem(data) {
      this.settingData = data
      await this.queryValueRecord(data.id)
      this.settingVisible = true
    },
    /* 删除参数 */
    deleteItem(id) {
      this.$params
        .deleteDictionary(id)
        .then((res) => {
          if (res.code === 200) {
            this.queryAllReportByType()
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((e) => {
          this.$message.error(e.toString())
        })
    },
    handleQuery() {
      this.queryAllReportByType()
    },
    resetQuery() {
      this.searvhValue.parameterName = null
      this.searvhValue.parameterCode = null
      this.currentCategoryId = null
      this.handleQuery()
      this.$refs.reportTree.setCurrentKey(null)
    },

    /* 搜索数据 */
    searchList(searvhValue) {
      this.searvhValue = searvhValue
      this.pageNum = 1
      this.queryAllReportByType()
    },

    /* 分类树点击 */
    handleNodeClick(data) {
      this.currentCategoryId = data.key
      this.queryAllReportByType()
    },
    /* 树搜索过滤 */
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    /* 获取目录 */
    getCatalogue() {
      this.loading = true
      this.$params
        .queryParemtFld()
        .then((res) => {
          if (res.code === 200) {
            this.categoryList = res.data
            this.$nextTick(() => {
              // this.$refs.reportTree.setCurrentKey(res.data[0].key)
              // this.currentCategoryId = res.data[0].key
              this.queryAllReportByType()
            })
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
          this.loading = false
        })
        .catch((e) => {
          this.$message.error(e.toString())
        })
    },
    nameToTitle(list) {
      if (!list || !list.length) return
      for (let item of list) {
        item.title = item.name
        if (item.children) {
          this.nameToTitle(item.children)
        }
      }
    },

    /* 提交创建类别 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this[formName]))
          console.log(params)
          if (params.parentId === '0') {
            delete params.parentId
          }

          if (this.isEdit) {
            params.id = params.parentId
            delete params.parentId
          }
          let apiName = this.isEdit ? 'editParemtFld' : 'addParemtFld'
          this.$params[apiName](params)
            .then((res) => {
              if (res.code === 200) {
                console.log(res)
                this.dialogFormVisible = false
                this.resetForm(formName)
                this.getCatalogue()
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
            })
            .catch((e) => {
              this.$message.error(e.toString())
            })
        }
      })
    },
    /* 清空创建类别 */
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this[formName].name = ''
      this[formName].parentId = ''
    },
    /* 新建目录 */
    addCategory(data) {
      this.isEdit = false
      if (data) {
        this.addInfo.parentId = data.key
      } else {
        this.addInfo.parentId = ''
      }
      this.dialogFormVisible = true
    },
    /* 删除目录 */
    deleteCategory(data) {
      this.$confirm('是否删除 ' + data.title + ' 参数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$params
            .deleParemtFld(data.key)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success('删除' + data.title + '成功！')
                this.getCatalogue()
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
            })
            .catch((e) => {
              this.$message.error(e.toString())
            })
        })
        .catch(() => {})
    },
    /* 修改目录 */
    editCategory(data) {
      this.isEdit = true
      this.addInfo.parentId = data.key
      this.addInfo.name = data.title
      this.dialogFormVisible = true
    },

    /* 查询类别报表 */
    queryAllReportByType() {
      this.loading2 = true
      let params = {
        // _v: 'list',
        folderId: this.currentCategoryId,
        pn: this.pageNum,
        ps: this.pageSize,
        parameterName: this.searvhValue.parameterName,
        parameterCode: this.searvhValue.parameterCode,
        parameterType: this.activeName,
      }
      if (!this.searvhValue.parameterName) {
        delete params.parameterName
      }

      this.$params
        .queryDictionaryAsList(params)
        .then((res) => {
          if (res.code === 200) {
            this.dataList = res.data.rows
            this.totalSize = res.data.total * 1
          } else if (res.code === 500) {
            this.dataList = []
            this.$message.info('报表为空！')
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
          this.loading2 = false
        })
        .catch((e) => {
          this.$message.error(e.toString())
        })
    },
    /* 查询记录 */
    queryValueRecord(id) {
      return new Promise((resolve) => {
        this.$params
          .queryParameterValue(id)
          .then((res) => {
            if (res.code === 200) {
              this.recordValueData = res.data
              let now = new Date().getTime()
              res.data.forEach((item) => {
                if (
                  new Date(item.effectiveStart).getTime() < now &&
                  new Date(item.effectiveEnd).getTime() > now
                ) {
                  this.currentUsingData = [item]
                }
              })
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            resolve()
          })
          .catch((e) => {
            this.$message.error(e.toString())
          })
      })
    },
    /* 删除记录 */
    deleteRecord(vid) {
      this.$params
        .deleteParameterValue(this.settingData.id, vid)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.queryValueRecord(this.settingData.id)
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((e) => {
          this.$message.error(e.toString())
        })
    },

    /* 新增值 */
    submitAddValue(formName) {
      let params = JSON.parse(JSON.stringify(this.addValueData))
      let temp = params.effectiveEnd.split(' ')
      params.effectiveEnd = temp[0] + ' 23:59:59'
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$params
            .addParameterValue(this.settingData.id, params)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success('提交成功')
                this.resetForm(formName)
                this.queryValueRecord(this.settingData.id)
                this.queryAllReportByType()
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
            })
            .catch((e) => {
              this.$message.error(e.toString())
            })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.addValueVisible = false
      // this.$nextTick(() => {
      //   this.settingVisible = false
      // })
    },
    /* 判断当前记录状态 */
    judgeRecordStatus(item) {
      let now = new Date().getTime()
      /* 使用中 */
      if (
        new Date(item.effectiveStart).getTime() < now &&
        new Date(item.effectiveEnd).getTime() > now
      ) {
        return ['', '使用中']
      }
      /* 待使用 */
      if (new Date(item.effectiveStart).getTime() > now) {
        return ['info', '未使用']
      }
      /* 已过期 */
      if (new Date(item.effectiveEnd).getTime() < now) {
        return ['danger', '已过期']
      }
    },
  },
}
</script>

<style lang="less">
.reportPopover {
  min-width: 0px;
  .popBox {
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
    align-items: center;
    // height: 60px;
    i {
      margin-bottom: 10px;
    }
  }
}
.dataReport {
  box-sizing: border-box;
  width: 100%;
  height: calc(100vh - 85px);
  .el-tree-node__children {
    font-size: 12px;
  }

  .el-tree-node__content {
    height: 40px;
    line-height: 40px;
    font-size: 13px;
  }

  .el-checkbox__input.is-disabled .el-checkbox__inner {
    display: none;
  }
  .categoryBox {
    box-shadow: 0 0 2px 1px rgb(199, 199, 199);
    overflow: auto;
    width: 240px;
    height: 100%;
    float: left;
    background-color: white;
    .categoryHeaderBox {
      height: 60px;
      padding-left: 22px;
      // line-height: 60px;
      align-items: center;
      font-size: 24px;
      position: relative;
      .iconTip {
        position: absolute;
        right: 10px;
        font-size: 16px;
        color: #409eff;
      }
    }
    .el-tree {
      margin-top: 0;
    }
    .el-tree-node__content {
      position: relative;
    }
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;

      width: 160px;
      .reportIconBox {
        position: absolute;
        right: 10px;
        i {
          margin: 0 3px;
        }
      }
    }
    .addCategoryBtnBox {
      height: 40px;
      width: 100%;
      i {
        font-size: 18px;
        font-weight: 600;
        color: #409eff;
        cursor: pointer;
      }
    }
  }
  .reportBox {
    overflow: hidden;
    height: 100%;
    box-sizing: border-box;
    padding: 16px;
    .contentBox {
      overflow: auto;
      .addBox {
        height: 170px;
        width: 230px;
        margin: 16px;
        box-sizing: border-box;
        border-radius: 6px;
        box-shadow: 0 0 2px rgb(168, 168, 168);
        .jstarfont {
          font-size: 66px;
          color: #409eff;
        }
        &:hover {
          box-shadow: 0 0 6px #409eff;
        }
      }
      .jstarfont {
        margin: 0 3px;
      }
      .addBox2 {
        height: 40px;
        width: 100%;
      }
      & > div {
        float: left;
      }
    }
  }
  .el-dialog__footer {
    border-top: 1px solid #e6ebf5;
    text-align: center;
    .el-button {
      margin: 10px 15px 0;
    }
  }
}
</style>